<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container">
        <!-- 语义化标签 SEO 方便于网格爬虫-->
        <table class="table table-striped">
            <caption>文章列表</caption>
            <!-- 表头 -->
            <thead>
                <tr>
                    <th>序号</th>
                    <th>标题</th>
                    <th>作者</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>

        <form name="postForm">
            <div class="form-group">
                <label for="titleInput">标题</label>
                <input type="text" class="form-control" name="title" id="titleInput" placeholder="请输入标题">
            </div>
            <div class="form-group">
                <label for="authorInput">作者</label>
                <input type="text" class="form-control" name="title" id="authorInput" placeholder="请输入作者">
            </div>
            <button class="btn btn-primary" type="submit">添加</button">
        </form>
    </div>

    <ul id="posts"></ul>
    <script>
        const oForm = document.forms["postForm"]
        oForm.addEventListener('submit', (event) => {
            event.preventDefault()//阻止默认行为
            const newPost = {
                "title": oForm.querySelector('#titleInput').value,
                "author": oForm.querySelector('#authorInput').value
            }
            fetch('http://localhost:3000/posts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(newPost)//把JSON对象转成字符串
            }).then(res => res.json())
            .then(data => {
                console.log(data);
            })
        })

        fetch('http://localhost:3000/posts')
            .then(res => res.json())
            .then(data => {
                document.querySelector('.table tbody').innerHTML =
                    data
                        .map(post => `
                        <tr>
                            <td>${post.id}</td>
                            <td>${post.title}</td>
                            <td>${post.author}</td>
                        </tr>
                    `)
                        .join('')
            })
    </script>
</body>

</html>